<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Notification;
use App\Notifications\ForgetPassword as fp;
class ForgetPassword extends Controller
{

    /**
     * 加载输入修改密码的邮箱地址
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function writeEmail(){
        //加载模板
     return view('forgetPassword.writepassword');

    }


    /**
     *
     * 发送邮件方法
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function sendEmail(Request $request){

        //获取post数据中的email
        $post = $request->all();
        //dd($post);
        //找到用户表中email等于post数据中的email的数据值
        $user = User::where('email',$post['email'])->first();
        //dd($user);
        //判断找到邮箱才可以发送
        if ($user){
            //找到用户数据才能发送邮件
            Notification::send($user,new fp($user['email']));
            //如果发送成功，设置闪存信息并加载一个页面
            session()->flash('success','邮件已发送至你的邮箱，请进入邮箱修改密码');
            //加载模板
            return view('forgetPassword.sendEmail');
        }

    }

    public function changePassword($email){
        //加载模板
        return view('forgetPassword.password',compact('email'));
    }


    public function change(Request $request){

        //获取post数据
        $post = $request->all();
        //定义验证规则
        $validator = $request->validate{
          [
              'password' => 'required|between:6,20|confirmed',
              'password_confirmation' => 'required|between:6,20',
          ]
        };
        //只有通过验证，才能修改密码
        //通过获取邮箱地址找到对应数据
        $user = User::where('email',$post['email'])->first();
        //修改密码
        $user->password = bcrypt($post['password']);
        //存入数据库
        $user->save();
        //设置闪存信息
        session()->flash('success','密码修改成功，请登录！');
        //跳转页面
        return redirect()->route('login');



    }







}
